import {createRouter, createWebHistory} from 'vue-router'
// import { useUserStore } from '@/assets'



// 设置路由
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            redirect: '/common/login'
        },
        {
            path: '/common/login',
            name: 'login',
            component: () => import('@/views/Login.vue')
        },
        {
            path: '/common/register',
            name: 'register',
            component: () => import('@/views/Register.vue')
        },
        {
            path: '/layout',
            name: 'layout',
            component: () => import('@/views/LayoutContainer.vue'),
            redirect: '/home',
            children: [
                {
                    path: '/home',
                    component: () => import('@/views/PageHome.vue')
                },
                {
                    path: '/saleManage/customers',
                    component: () => import('@/views/CustomersPage.vue')
                },
                {
                    path: '/saleManage/employees',
                    component: () => import('@/views/EmployeePage.vue')
                },
                {
                    path: '/saleManage/contracts',
                    component: () => import('@/views/ContractPage.vue')
                },
                {
                    path: '/warehouse/goods',
                    component: () => import('@/views/ProductPage.vue')
                },
                {
                    path: '/warehouse/orders',
                    component: () => import('@/views/SendOrder.vue')
                },
                {
                    path: '/warehouse/purchaseOrders',
                    component: () => import('@/views/purchaseOrdersPage.vue')
                },
                {
                    path: '/saleManage/turnover',
                    component: () => import('@/views/TurnoverView.vue')
                },
                {
                    path: '/sale/myOrders',
                    component: () => import('@/views/MyOrdersView.vue')
                },
                {
                    path: '/sale/mySales',
                    component: () => import('@/views/MysalesView.vue')
                },

            ]
        }
    ]
})

// router.beforeEach((to) => {
//     const userStore = useUserStore()
//     if (!userStore.isLogin && to.path !== '/login' && to.path != '/home')
//         return '/login'
// })
// 添加路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token');
    const publicPages = ['/common/login', '/common/register']; // 公开页面
    const authRequired = !publicPages.includes(to.path); // 需要授权的页面

    if (authRequired && !token) {
        next({ name: 'login' }); // 如果未登录，重定向到登录页面
    } else {
        next(); // 放行
    }
});

export default router
